var setting = {
	data : {
		simpleData : {
			enable : true,
		}
	},
	callback : {
		onClick : showTaskConfig
	}
};
var taskId=0,taskName,zTree,sche;
$(function(){
	getTaskTree();
	$("#myAudio").initAudio();
})

function getTaskTree(){
	$.ajax({
		type : "post",
		url : "taskTree",
		dataType : "json",
		success : function(data){
			if(data.msg == "success"){
				zTree = $.fn.zTree.init($("#tree"), setting, data.datas);
				zTree.selectNode(zTree.getNodeByParam("id",taskId,null));
			}
		}
	});
}

function showTaskConfig(event, treeId, treeNode){
	if(!treeNode.isParent){
		taskId = treeNode.id;
		taskName = treeNode.name;
		var activeLi = $("#generalTab > li.active").attr("name");
		if(activeLi == 'all-tab'){
			listAllLogs();
		}else if(activeLi == 'success-tab'){
			$("#ths").html('');
			$("#successLogs").html('');
			listFields(1);
		}else{
			listFailLogs(1);
		}
	}else{
		zTree.expandNode(treeNode);
	}
}

function listAllLogs(){
	if(!checkEmpty(taskName)){
		$.ajax({
			type : "post",
			data:{taskId:taskId,taskName:taskName},
			url : "listAllLogs",
			dataType : "json",
			success : function(data){
				if(data.msg == "success"){
					var html = '<tr>'
								+'<td><label>1</label></td>'
								+'<td><label>'+data.successCount+'</label></td>'
								+'<td><label>'+data.failCount+'</label></td>';
					sche = data.schedule;
					if(sche == null || sche.isAuto == 0){
						html += '<td><label>手动</label></td>'
								+'<td><label>无</label></td>';
					}else{
						html += '<td><label>自动</label></td>'
								+'<td><label>'+sche.cron+'</label></td>';
					}
					if(data.status == 'Init' || data.status == 'Stopped'){
						html += '<td><label>未运行</label></td>'
								+'<td><button onclick="editSchedule();" type="button" style="margin-right:5px;" class="btn btn-success btn-xs">更改执行策略</button>';
//						if(sche == null || sche.isAuto == 0){
							html += '<button onclick="start();" type="button" class="btn btn-success btn-xs">开始运行</button></td>';
//						}
					}else if(data.status == 'Paused'){
						html += '<td><label>已暂停</label></td>'
								+'<td><button onclick="reRun();" type="button" style="margin-right:5px;" class="btn btn-success btn-xs">继续运行</button>'
								+'<button onclick="stop();" type="button" class="btn btn-red btn-xs">停止</button></td>'
					}else{
						html += '<td><label>运行中</label></td>'
							+'<td><button onclick="pause();" type="button" style="margin-right:5px;" class="btn btn-red btn-xs">暂停</button>'
							+'<button onclick="stop();" type="button" class="btn btn-red btn-xs">停止</button></td>'
					}
					html +='</tr>';
					$("#logs").html(html);
				}
			}
		});
	}
	
}

function start(){
	layer.load();
	var param = {};
	param["taskId"] = taskId;
	param["isTestRun"] = false;
	if(sche != null){
		param["isAuto"] = sche.isAuto;
		param["cron"] = sche.cron;
	}
	$.ajax({
		type : "post",
		url : "run",
		data : param,
		dataType : "text",
		success : function(data) {
			if(data == 'true'){
//				layer.msg("启动成功");
				setTimeout(listAllLogs,200);
			}else{
				layer.msg("启动失败");
			}
			layer.closeAll('loading');
		}
	});
}

function stop(){
	layer.load();
	$.ajax({
		type : "post",
		url : "stop",
		data : {
			"taskId":taskId
		},
		dataType : "text",
		success : function(data) {
			if(data == 'true'){
				setTimeout(listAllLogs,200);
			}else{
				layer.msg("停止失败");
			}
			layer.closeAll('loading');
		}
	});
}

function pause(){
	layer.load();
	$.ajax({
		type : "post",
		url : "pause",
		data : {
			"taskId":taskId
		},
		dataType : "text",
		success : function(data) {
			if(data == 'true'){
				setTimeout(listAllLogs,200);
			}else{
				layer.msg("暂停失败");
			}
			layer.closeAll('loading');
		}
	});
}

function reRun(){
	layer.load();
	$.ajax({
		type : "post",
		url : "reRun",
		data : {
			"taskId":taskId
		},
		dataType : "text",
		success : function(data) {
			if(data == 'true'){
				setTimeout(listAllLogs,200);
			}else{
				layer.msg("恢复运行失败");
			}
			layer.closeAll('loading');
		}
	});
}

var fields = {};
function listFields(){
	if(taskId != 0){
		$.ajax({
			type : "post",
			url : "taskFieldPageListByTaskId",
			data : {
				"taskId":taskId,
				"status":0,
				"start":-1
			},
			dataType : "json",
			success : function(data) {
				if(data.msg == 'success'){
					$.each(data.datas,function(k,v){
						fields[v.enName] = v.cnName;
					});
					fields['createTime'] = '采集时间';
					listSuccessLogs(1);
				}
			}
		})
	}
	
}

function listSuccessLogs(){
	var currPage = arguments[0];
	$.ajax({
		type : "post",
		url : "listSuccessLogs",
		data : {
			"taskName":taskName,
			"start":currPage
		},
		dataType : "json",
		success : function(data) {
			if(data.msg == 'success'){
				var dataHtml = '';
				var thHtml = '<tr><th>序号</th>';
				var ths = [];
				$.each(data.datas,function(k,v){
					if(k == 0){
						$.each(v,function(th,value){
							if(th !='_id' && th != '_class'){
								if(th != 'originalUrl'){
									thHtml += '<th>'+fields[th]+'</th>';
									ths.push(th);
								}
							}
						});
						ths.push('originalUrl');
						thHtml += '<th>操作</th>';
						thHtml += '</tr>';
						$("#ths").html(thHtml);
					}
					dataHtml += '<tr><td>'+(k+1)+'</td>';
					for(var i=0;i<ths.length;i++){
						if(ths[i] != 'originalUrl'){
							if(v[ths[i]] != null && v[ths[i]]){
								dataHtml += '<td title="'+v[ths[i]]+'"><label>'+v[ths[i]].substring(0,10)+'</label></td>';
							}else{
								dataHtml += '<td><label></label></td>';
							}
						}else{
							dataHtml += '<td>'
										+'<a style="float:left;margin-bottom:5px;margin-right:5px;" target="blank" type="button" class="btn btn-success btn-xs" href="'+v[ths[i]]+'">查看原网页</a>'
										+'<button onclick="listImgs(\''+v["_id"]+'\')" style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-success btn-xs">查看图片</button>'
										+'<button onclick="listVideos(\''+v["_id"]+'\')" style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-success btn-xs">查看视频</button>'
										+'<button onclick="listAudios(\''+v["_id"]+'\')" style="float:left;margin-right:5px;margin-bottom:5px;" type="button" class="btn btn-success btn-xs">查看音频</button>'
										+'<button onclick="listFiles(\''+v["_id"]+'\')" style="float:left;" type="button" class="btn btn-success btn-xs">查看附件</button>'
										+'</td>';
						}
					}
					dataHtml+= '</tr>';
				});
				if(dataHtml == ''){
					dataHtml = html = '<tr><td colspan="'+ths.length+'">暂无数据</td></tr>';;
				}
				$("#successLogs").html(dataHtml);
				laypage({
					cont : document.getElementById('pageSuccess'), //容器。值支持id名、原生dom对象，jquery对象,
					pages : data.pages, //总页数
					skip : true, //是否开启跳页
					skin : 'molv', //加载内置皮肤，也可以直接赋值16进制颜色值，如:#c00
					curr : currPage,
					last: data.pages,
					groups : 6,//连续显示分页数
					jump : function(obj, first) { //触发分页后的回调
						if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
							listSuccessLogs(obj.curr);
						}
					}
				});
			}else{
				layer.msg("获取数据失败");
			}
		}
	});
}

function listFailLogs(){
	if(taskId != 0){
		$.ajax({
			type : "post",
			url : "listFailLogs",
			data : {
				"taskId":taskId,
				"start":arguments[0]
			},
			dataType : "json",
			success : function(data) {
				if(data.msg == 'success'){
					var html = '';
					$.each(data.datas,function(k,v){
						html += '<tr><td><input type="checkbox" name="check" value='+v.id+' /></td>'
									+'<td>'+(k+1)+'</td>'
									+'<td><label>'+v.url+'</label></td>'
									+'<td url="'+v.url+'" id="'+v.id+'">'
									+'<button type="button" class="btn btn-blue btn-xs" onclick="retry(\''+v.id+'\');">重采</button>&nbsp;&nbsp;&nbsp;'
									+'<button type="button" class="btn btn-red btn-xs" onclick="delOne(\''+v.id+'\');">删除</button>&nbsp;&nbsp;&nbsp;'
									+'</td></tr>';
					});
					if(html == ''){
						html = '<tr><td colspan="3">暂无数据</td></tr>';
					}
					$("#failLogs").html(html);
					laypage({
						cont : document.getElementById('pageFail'), //容器。值支持id名、原生dom对象，jquery对象,
						pages : data.pages, //总页数
						skip : true, //是否开启跳页
						skin : 'molv', //加载内置皮肤，也可以直接赋值16进制颜色值，如:#c00
						curr : currPage,
						last: data.pages,
						groups : 6,//连续显示分页数
						jump : function(obj, first) { //触发分页后的回调
							if (!first) { //点击跳页触发函数自身，并传递当前页：obj.curr
								listFailLogs(obj.curr);
							}
						}
					});
				}else{
					layer.msg("获取数据失败");
				}
				
			},
			error : function(data) {
				layer.msg("获取数据失败");
			}
		});
	}
	
}

function editSchedule(schedule){
	$("#id").val("");
	$("#isAuto").val("0");
	$("#cron").val("");
	layer.open({
		title:"定制执行策略",
		type: 1,
		area : [ '600px', '510px' ],
		content: $('#schedule'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
		btn: ['保存', '关闭'],
		yes: function(index){
			var isAuto = $.trim($("#isAuto").val());
			var cron = $.trim($("#cron").val());
			if(isAuto == '1' && (cron == '' || cron.length == 0)){
				layer.msg('请输入定时策略');
				return;
			}
			var sch = {};
			var id = $("#id").val();
			if(id != ""){
				sch["id"] = id;
			}
			sch["isAuto"] = isAuto;
			sch["taskId"] = taskId;
			sch["cron"] = cron;
			$.post("saveOrUpdateSchedule",sch, function(data) {
				if(!data.msg){
					layer.msg("保存失败");
				}else{
					layer.msg("保存成功");
					layer.close(index);
					listAllLogs();
				}
			});
			
		},
		close: function(){
			
		},
		success:function(){
			if(sche != null){
				$("#id").val(sche.id);
				$("#isAuto").val(sche.isAuto);
				$("#cron").val(sche.cron);
			}
		}
	});
}

function exportData(isAll){
	layer.load();
	$.post("export",{taskId:taskName,isAll:isAll}, function(data) {
		if(data.msg == 'false'){
			layer.msg("导出失败");
		}else{
			layer.msg("导出成功");
			window.location.href = "downExportXml?filePath="+data.filePath;
		}
		layer.closeAll('loading');
	});
}